package com.jcj.jcjmq.server.controller;

import com.jcj.jcjmq.model.Message;
import com.jcj.jcjmq.model.Result;
import com.jcj.jcjmq.server.MessageQueue;
import com.jcj.jcjmq.server.MessageSubscription;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/jcjmq")
public class MqServerController {
    //send
    @RequestMapping("/send")
    public Result send(@RequestParam String topic, @RequestBody Message<String> message) {
        int send = MessageQueue.send(topic, message);
        return Result.ok(send + "");
    }


    //recv
    @RequestMapping("/recv")
    public Result<Message> recv(@RequestParam String topic, @RequestParam String consumerId) {
        Message<?> recv = MessageQueue.recv(topic, consumerId);
        return Result.msg(recv);
    }


    //recv
    @RequestMapping("/batchRecv")
    public Result<List<Message<?>>> batchRecv(@RequestParam String topic, @RequestParam String consumerId, @RequestParam(defaultValue = "100") Integer size) {
        List<Message<?>> recv = MessageQueue.batchRecv(topic, consumerId, size);
        return Result.msg(recv);
    }

    //ack
    @RequestMapping("/ack")
    public Result ack(@RequestParam String topic, @RequestParam String consumerId, @RequestParam Integer offset) {
        int ack = MessageQueue.ack(topic, consumerId, offset);
        return Result.ok(ack + "");
    }

    //sub
    @RequestMapping("/sub")
    public Result sub(@RequestParam String topic, @RequestParam String consumerId) {
        MessageQueue.sub(new MessageSubscription(topic, consumerId, -1));
        return Result.ok();
    }

    //unsub
    @RequestMapping("/unsub")
    public Result unsub(@RequestParam String topic, @RequestParam String consumerId) {
        MessageQueue.unsub(new MessageSubscription(topic, consumerId, -1));
        return Result.ok();
    }
}
